package sdk.webview.fmc.com.fmcsdk.presenter;

import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;
import sdk.webview.fmc.com.fmcsdk.R;
import sdk.webview.fmc.com.fmcsdk.base.BaseActivity;
import sdk.webview.fmc.com.fmcsdk.base.BaseData;
import sdk.webview.fmc.com.fmcsdk.base.BasePresenter;
import sdk.webview.fmc.com.fmcsdk.base.CommonApi;
import sdk.webview.fmc.com.fmcsdk.base.UserApi;
import sdk.webview.fmc.com.fmcsdk.bean.AgreementBean;
import sdk.webview.fmc.com.fmcsdk.bean.AgreementEntity;
import sdk.webview.fmc.com.fmcsdk.bean.CheckByUnamepwdResponse;
import sdk.webview.fmc.com.fmcsdk.bean.IconBean;
import sdk.webview.fmc.com.fmcsdk.bean.JpushAliasBean;
import sdk.webview.fmc.com.fmcsdk.bean.LoginInfo;
import sdk.webview.fmc.com.fmcsdk.bean.LoginParamBean;
import sdk.webview.fmc.com.fmcsdk.bean.ModfiyPassword;
import sdk.webview.fmc.com.fmcsdk.bean.SysKeyDescBean;
import sdk.webview.fmc.com.fmcsdk.bean.SysSettingsInfoBean;
import sdk.webview.fmc.com.fmcsdk.bean.SystemSetting;
import sdk.webview.fmc.com.fmcsdk.bean.User;
import sdk.webview.fmc.com.fmcsdk.bean.UserAgreement;
import sdk.webview.fmc.com.fmcsdk.bean.XiyouLoginBean;
import sdk.webview.fmc.com.fmcsdk.interfaces.LoginView;
import sdk.webview.fmc.com.fmcsdk.util.AESUtil;
import sdk.webview.fmc.com.fmcsdk.util.Constant;
import sdk.webview.fmc.com.fmcsdk.util.DESCoder;
import sdk.webview.fmc.com.fmcsdk.util.DesUtil;
import sdk.webview.fmc.com.fmcsdk.util.ImageUtils;
import sdk.webview.fmc.com.fmcsdk.util.PreferencesHelper;
import sdk.webview.fmc.com.fmcsdk.util.SM2Utils;
import sdk.webview.fmc.com.fmcsdk.util.StringUtils;
import sdk.webview.fmc.com.fmcsdk.util.ToastUtils;
import sdk.webview.fmc.com.fmcsdk.util.Url;
import sdk.webview.fmc.com.fmcsdk.util.UserHelper;
import sdk.webview.fmc.com.fmcsdk.util.Utility;
import sdk.webview.fmc.com.fmcsdk.util.XLog;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.observer.ApiFactory;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.observer.ResponseTransformer;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.subscriber.ResponseSubscriber;

/**
 * Created by ydm on 2017/8/4.
 */

public class LoginPresenter extends BasePresenter<LoginView> {
    private String username;
    private String password;
    public String captchaKey = "";
    public String codeStr = "";
    /**
     * 手机唯一识别码
     */
    private String imei = "";

    private String authType = "1";


    public void getRandomUUID() {
        UUID uuid = UUID.randomUUID();
        captchaKey = uuid.toString();
    }


    /**
     * 登录
     *
     * @param username  用户名
     * @param passwords 密码
     * @param authType
     * @param phoneCode
     */
    public void login(final String username, final String passwords, final String authType, final String phoneCode) {

        String appName = (String) Utility.getMetaData(view.getViewContext(), Constant.APP_NAME);
        if (Constant.APP_NAME_ZSJ.equals(appName)) {
            getSM2Key(username, passwords);
        } else {
            loginSystem(username, passwords, authType, phoneCode);

        }

    }

    public void getSM2Key(final String musername, final String mpasswords) {
        view.showLoading();
        getApi(UserApi.class).getSM2Key(getDefaultAddress() + Url.GET_SM2KEY, Url.XMLHTTPREQUEST)
                .compose(new ResponseTransformer<>(this.<ModfiyPassword>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<ModfiyPassword>() {
                    @Override
                    public void success(ModfiyPassword baseData) {
                        loginSystemChar(baseData.getRecord().getPublicKey(), musername, mpasswords);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }

                    @Override
                    public void onRequestAgain() {
                    }
                });
    }



    public void getSM2Key(final String initialPassword, final String newPassword, String againPassword) {
        view.showLoading();
        getApi(UserApi.class).getSM2Key(getDefaultAddress() + Url.GET_SM2KEY, Url.XMLHTTPREQUEST)
                .compose(new ResponseTransformer<>(this.<ModfiyPassword>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<ModfiyPassword>() {
                    @Override
                    public void success(ModfiyPassword baseData) {
                        modifyPasswordChar(baseData.getRecord().getPublicKey(), initialPassword, newPassword);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }

                    @Override
                    public void onRequestAgain() {
                    }
                });
    }


    public void modifyPasswordChar(final String key, final String initialPassword, final String newPassword) {
        view.showLoading();
        getApi(UserApi.class).modifyPasswordChar(getDefaultAddress() + Url.MODIFY_PASSWORD, Url.XMLHTTPREQUEST, UserHelper.getToken(), key, SM2Utils.encode(key, initialPassword), SM2Utils.encode(key, newPassword))
                .compose(new ResponseTransformer<>(this.<BaseData>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<BaseData>(view) {
                    @Override
                    public void success(BaseData baseData) {
                        view.ToastMessage(R.string.change_success);
                    }

                    @Override
                    public void onRequestAgain() {
                        modifyPasswordChar(key, SM2Utils.encode(key, initialPassword), SM2Utils.encode(key, newPassword));
                    }
                });
    }

    /**
     * 登录
     *
     * @param username
     * @param passwords
     * @param authType  1：账号密码登录  19：手机短信验证码登录
     * @param phoneCode (加密前字符串示例：13971133023&123498)
     */
    private void loginSystem(String username, final String passwords, String authType, String phoneCode) {

        if ("1".equals(authType)) {
            if (TextUtils.isEmpty(username)) {
                view.ToastMessage(R.string.msg_login_usernameisnull);
                return;
            }
            if (TextUtils.isEmpty(passwords)) {
                view.ToastMessage(R.string.msg_login_psdisnull);
                return;
            }
        }

        if ("19".equals(authType)) {
            PreferencesHelper.saveData("isOkGetSysInfo", "true");
        }

        this.username = username;
        //加密
        this.password = new String(DESCoder.encodeToBase64(passwords));
        /**显示提示框*/
        view.showLoading();
        //如果未获取到手机识别码，自定义一个
        if (TextUtils.isEmpty(Utility.getIMEI(view.getViewContext()))) {
            imei = username + "pad";
        } else {
            imei = Utility.getIMEI(view.getViewContext());
        }

        Map<String, String> map = new HashMap<>();
        LoginParamBean bean = new LoginParamBean();
        bean.setClientType("1");
        bean.setImei(imei);
        bean.setBrand(Build.BRAND);
        bean.setOs("android");
        bean.setOsVersion(Build.VERSION.RELEASE);
        bean.setVersion("1.0");
        Gson gson = new Gson();
        String s = gson.toJson(bean);

        //phoneCode  (加密前字符串示例：13971133023&123498)
        map.put("username", "1".equals(authType) ? username : "");
        map.put("password", "1".equals(authType) ? passwords : "");
        map.put("attachment", s);
        map.put("appUniqueNo", Utility.getIMEI(view.getViewContext()));

        map.put("setUserLang", String.valueOf(BaseActivity.setLang));
        map.put("accountLockNum", UserHelper.getSysSettingsValueBycode("ACCOUNT_LOCK_THRESHOLD")); // 账户锁定阈值(次)
        if (!TextUtils.isEmpty(captchaKey)) {
            map.put("captchaValue", codeStr);
            map.put("captchaKey", captchaKey);
            map.put("captcha", "1");
        }

        map.put("loginTimeOut", UserHelper.getSysSettingsValueBycode("LOGIN_TIME_OUT")); //登录保持时长(小时)
        map.put("defaultLang", getSharedPrefs().getString("lang_code", "zh-CN"));
        map.put("authType", authType);
        map.put("phoneCode", "1".equals(authType) ? "" : phoneCode);

        XLog.i("setLang:" + String.valueOf(BaseActivity.setLang));
        XLog.i("bena:" + s);
        Map<String, RequestBody> requestBodyMap = new HashMap<>();
        for (String key : map.keySet()) {
            RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),
                    map.get(key) == null ? "" : map.get(key));
            requestBodyMap.put(key, requestBody);
        }

        String appName = (String) Utility.getMetaData(view.getViewContext(), Constant.APP_NAME);
        if (Constant.APP_NAME_SZW.equals(appName)) {
            authType = "9";
        }


        getApi(UserApi.class).userLogin2(getDefaultAddress() + Url.LOGIN, Url.XMLHTTPREQUEST, authType, requestBodyMap)
                .compose(new ResponseTransformer<>(this.<LoginInfo>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<LoginInfo>(view) {
                    @Override
                    public void success(LoginInfo baseData) {
                        BaseActivity.setLang = 0;
                        //获取用户信息
                        getUserInfo(baseData.getRecord().getAccessToken(), passwords);
                    }

                    @Override
                    public void onRequestAgain() {
                    }

                    /**请求成功但业务返回失败，自己处理dialog的隐藏和消息提示，因为系统设置下载图片的时候有空白期，需要在下载完成之后才能取消dialog*/
                    @Override
                    public boolean operationError(LoginInfo loginInfo, String status, String message) {
                        ToastUtils.showShort(view.getViewContext(), message);
                        view.hideLoading();
                        return true;
                    }

                    @Override
                    public void onError(Throwable e) {

                        view.connentError(e);
                        view.hideLoading();
                        super.onError(e);
                    }
                });
    }


    private void loginSystemChar(String publickey, String username, final String passwords) {
        if (TextUtils.isEmpty(username)) {
            view.ToastMessage(R.string.msg_login_usernameisnull);
            return;
        }
        if (TextUtils.isEmpty(passwords)) {
            view.ToastMessage(R.string.msg_login_psdisnull);
            return;
        }

        Log.e("shuchang", "username---->" + username + ",,,,passwords--->" + passwords);

        this.username = username;
        //加密
        this.password = new String(DESCoder.encodeToBase64(passwords));
        /**显示提示框*/
        view.showLoading();
        //如果未获取到手机识别码，自定义一个
        if (TextUtils.isEmpty(Utility.getIMEI(view.getViewContext()))) {
            imei = username + "pad";
        } else {
            imei = Utility.getIMEI(view.getViewContext());
        }

        Map<String, String> map = new HashMap<>();
        LoginParamBean bean = new LoginParamBean();
        bean.setClientType("1");
        bean.setImei(imei);
        bean.setBrand(Build.BRAND);
        bean.setOs("android");
        bean.setOsVersion(Build.VERSION.RELEASE);
        bean.setVersion("1.0");
        Gson gson = new Gson();
        String s = gson.toJson(bean);
//        map.put("authType","1");
        map.put("username", username);
        map.put("publicKey", publickey);
        map.put("password", SM2Utils.encode(publickey, passwords));
        map.put("attachment", s);
        map.put("appUniqueNo", Utility.getIMEI(view.getViewContext()));
        map.put("defaultLang", getSharedPrefs().getString("lang_code", "zh-CN"));
        map.put("setUserLang", String.valueOf(BaseActivity.setLang));
        if (!TextUtils.isEmpty(captchaKey)) {
            map.put("captchaValue", codeStr);
            map.put("captchaKey", captchaKey);
            map.put("captcha", "1");
        }

        XLog.i("setLang:" + String.valueOf(BaseActivity.setLang));
        XLog.i("bena:" + s);
        Map<String, RequestBody> requestBodyMap = new HashMap<>();
        for (String key : map.keySet()) {
            RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),
                    map.get(key) == null ? "" : map.get(key));
            requestBodyMap.put(key, requestBody);
        }

        String appName = (String) Utility.getMetaData(view.getViewContext(), Constant.APP_NAME);
        if (Constant.APP_NAME_SZW.equals(appName)) {
            authType = "9";
        }


        getApi(UserApi.class).userLogin2(getDefaultAddress() + Url.LOGIN, Url.XMLHTTPREQUEST, authType, requestBodyMap)
                .compose(new ResponseTransformer<>(this.<LoginInfo>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<LoginInfo>(view) {
                    @Override
                    public void success(LoginInfo baseData) {
                        BaseActivity.setLang = 0;
                        //获取用户信息
                        getUserInfo(baseData.getRecord().getAccessToken(), passwords);
                    }

                    @Override
                    public void onRequestAgain() {
                    }

                    /**请求成功但业务返回失败，自己处理dialog的隐藏和消息提示，因为系统设置下载图片的时候有空白期，需要在下载完成之后才能取消dialog*/
                    @Override
                    public boolean operationError(LoginInfo loginInfo, String status, String message) {
                        ToastUtils.showShort(view.getViewContext(), message);
                        view.hideLoading();
                        return true;
                    }

                    @Override
                    public void onError(Throwable e) {

                        view.connentError(e);
                        view.hideLoading();
                        super.onError(e);
                    }
                });
    }


    /**
     * 获取用户信息
     */
    public void getUserInfo(final String accessToken, final String passwords) {
        Log.e("Cook", getDefaultAddress());
        getApi(UserApi.class).getUserInfo(getDefaultAddress() + Url.GET_USER_INFO, Url.XMLHTTPREQUEST, accessToken)
                .compose(new ResponseTransformer<>(this.<User>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<User>(view) {
                    @Override
                    public void success(User baseData) {
                        baseData.getRecord().setPassword(passwords);
                        /**保存用户信息*/
                        try {
                            String tokenStr = DesUtil.encode(accessToken);
                            baseData.getRecord().setAccessToken(tokenStr);

                        } catch (Exception e) {
                            e.printStackTrace();
                            baseData.getRecord().setAccessToken(accessToken);
                        }
                        AgreementBean agreementBean = PreferencesHelper.getData(AgreementBean.class);
                        if (agreementBean != null) {
                            if (TextUtils.equals(agreementBean.getIsCustom(),"1")) {
                                //获取用户版本号
                                getUserAgreement(accessToken, passwords, baseData);

                            } else {
                                setUserInfo(baseData, accessToken);
                            }
                        } else {
                            setUserInfo(baseData, accessToken);
                        }


                    }

                    @Override
                    public void onRequestAgain() {
                        getUserInfo(accessToken, passwords);
                    }

                    @Override
                    public boolean operationError(User user, String status, String message) {
                        ToastUtils.showShort(view.getViewContext(), message);
                        view.hideLoading();
                        return true;
                    }

                    @Override
                    public void onError(Throwable e) {
                        view.connentError(e);
                        view.hideLoading();
                        super.onError(e);
                    }
                });
    }

    private void setUserInfo(User baseData, String accessToken) {
        UserHelper.saveUser(baseData);
        /**获取强弱项密码*/
        getPwdLevel(accessToken);
        /***获取权限*/
        getSystemSettingInfo(accessToken);
        view.loginSuccessSuccess(baseData.getRecord().getUserId());

        //设置系统返回的多语言默认值
        String defaultLang = baseData.getRecord().getDefaultLang();
        if (!TextUtils.isEmpty(defaultLang)) {
            XLog.i(defaultLang);
            String[] stringArray = view.getViewContext().getResources().getStringArray(R.array.multi_language_code);
            for (int i = 0; i < stringArray.length; i++) {
                if (stringArray[i].equalsIgnoreCase(defaultLang)) {
                    getSharedPrefs().edit().putInt("lang", i).apply();
                    getSharedPrefs().edit().putString("lang_code", defaultLang).apply();
                }
            }
        }
    }


    private void getUserAgreement(final String accessToken, final String password, final User baseData) {

        getApi(UserApi.class).getUserAgreement(getDefaultAddress() + Url.FIND_LAST_OPERATELOG, Url.XMLHTTPREQUEST, accessToken, Long.parseLong(baseData.getRecord().getUserId()), 1)
                .compose(new ResponseTransformer<>(this.<UserAgreement>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<UserAgreement>() {
                    @Override
                    public void success(UserAgreement userAgreement) {

                        AgreementBean agreementBean = PreferencesHelper.getData(AgreementBean.class);
                        if (agreementBean != null) {


                            //如果当前版本内容为空，直接登陆
                            if (TextUtils.isEmpty(agreementBean.getContent())) {
                                setUserInfo(baseData, accessToken);
                                return;
                            }
                            boolean isLook = getSharedPrefs().getBoolean(Constant.LOOK_AGREEMENT, false);
                            //如果用户第一次登陆，直接弹出协议界面
                            if (userAgreement.getRecord() == null) {


                                if (isLook) {
                                    insertArgeement(accessToken, baseData, 0);
                                } else {
                                    view.AgreementDiffer();
                                }
                                return;

                            }


                            //如果版本号一致直接去登陆
                            if (agreementBean.getVersion().equals(userAgreement.getRecord().getRemark())) {
                                setUserInfo(baseData, accessToken);
                            } else {
                                if (isLook) {
                                    insertArgeement(accessToken, baseData, 0);
                                } else {
                                    view.AgreementDiffer();
                                }
                                //如果不一致的话让客户浏览最新协议，

                                //将最新协议插入到用户数据里
//                                insertArgeement(accessToken,baseData,1);
                            }


                        }


                    }

                    @Override
                    public void onRequestAgain() {
                    }

                    @Override
                    public boolean operationError(UserAgreement user, String status, String message) {
                        view.hideLoading();
                        return true;
                    }

                    @Override
                    public void onError(Throwable e) {
                        view.hideLoading();
                        super.onError(e);
                    }
                });
    }


    private void insertArgeement(final String accessToken, final User user, final int firstInsert) {
        Gson gson = new Gson();

        AgreementBean agreementBean = PreferencesHelper.getData(AgreementBean.class);
        AgreementEntity entity = new AgreementEntity();
        entity.setRemark(agreementBean.getVersion());
        entity.setModifyContent("AGREEMENT");
        entity.setStaffId(Long.parseLong(user.getRecord().getUserId()));
        entity.setId(0);
        entity.setOrgId(0);
        entity.setModifyBy(1);
        //转为json数据发送，用raw方式传参。后台定义的


        String s1 = gson.toJson(entity);

        String s2 = "{\"entity\":" + s1 + "}";
        RequestBody requestBody = RequestBody.create(MediaType.parse("raw"), s2);
        getApi(UserApi.class).insertArgeement(getDefaultAddress() + Url.ADD_STAFF_OPERATIONLOG, Url.XMLHTTPREQUEST, accessToken, "application/json", requestBody)
                .compose(new ResponseTransformer<>(this.<BaseData>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<BaseData>() {
                    @Override
                    public void success(BaseData baseData) {

                        if (firstInsert == 0) {
                            setUserInfo(user, accessToken);
                        } else {

                            view.AgreementDiffer();

                        }

                        view.hideLoading();
                    }

                    @Override
                    public void onRequestAgain() {
                    }

                    @Override
                    public boolean operationError(BaseData user, String status, String message) {
                        view.hideLoading();
                        return true;
                    }

                    @Override
                    public void onError(Throwable e) {
                        view.hideLoading();
                        super.onError(e);
                    }
                });
    }


    /**
     * 获取系统信息设置
     *
     * @param accessToken
     */
    private void getSystemSettingInfo(final String accessToken) {
        getApi(UserApi.class).getSystemSettingInfo(getDefaultAddress() + Url.GET_SYS_SETTING, Url.XMLHTTPREQUEST, accessToken)
                .compose(new ResponseTransformer<>(this.<SystemSetting>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<SystemSetting>() {
                    @Override
                    public void success(SystemSetting baseData) {
                        /**启动页图片路径*/
                        String app_start_page_img = baseData.getRecord().getAPP_START_PAGE_IMG();
                        /**关于的图片路径*/
                        String about_page_img = baseData.getRecord().getABOUT_PAGE_IMG();
                        try {
                            if (!TextUtils.isEmpty(app_start_page_img)) {
                                //启动页下载
                                JSONObject startImg = new JSONObject(app_start_page_img);
                                String startUrl = startImg.optString("url");
                                //截取图片部分路径作为下载图片的名称
                                if (!TextUtils.isEmpty(startUrl)) {
                                    String startStr = startUrl.substring(startUrl.lastIndexOf("/") + 1);
                                    String[] startArray = startStr.split("\\.");
                                    if (!startUrl.startsWith("http")) {
                                        startUrl = getDefaultAddress() + startUrl;
                                    }
                                    ImageUtils.downloadImage(view.getViewContext(), startUrl, startArray[0] + "_" + Constant.START_BG, getSharedPrefs());
                                }
                            }

                            if (!TextUtils.isEmpty(about_page_img)) {
                                //下载关于图片
                                JSONObject aboutImg = new JSONObject(about_page_img);
                                String aboutUrl = aboutImg.optString("url");
                                //截取图片部分路径作为下载图片的名称
                                if (!TextUtils.isEmpty(aboutUrl)) {
                                    String aboutStr = aboutUrl.substring(aboutUrl.lastIndexOf("/") + 1);
                                    String[] aboutArray = aboutStr.split("\\.");
                                    if (!aboutUrl.startsWith("http")) {
                                        aboutUrl = getDefaultAddress() + aboutUrl;
                                    }
                                    ImageUtils.downloadImage(view.getViewContext(), aboutUrl, aboutArray[0] + "_" + Constant.ABOUT_BG, getSharedPrefs());
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                        PreferencesHelper.saveData(baseData);

                        //设置值，以后显示欢迎界面
                        getSharedPrefs().edit().putString(Constant.FIRST_OPEN, "noFirstOpen").apply();
                        //登陆成功
                        getSharedPrefs().edit().putBoolean(Constant.ISLOGIN, true).apply();

                        getSharedPrefs().edit().putString(Constant.IMAGE_SIZE, baseData.getRecord().getCOMPRESSION_SIZE()).apply();

                        view.loginSuccess();
                    }

                    @Override
                    public void onError(Throwable e) {
                        view.connentError(e);
                        view.hideLoading();
                        super.onError(e);
                    }

                    @Override
                    public void onRequestAgain() {
                        getSystemSettingInfo(accessToken);
                    }

                    @Override
                    public boolean operationError(SystemSetting systemSetting, String status, String message) {
                        ToastUtils.showShort(view.getViewContext(), message);
                        view.hideLoading();
                        return true;
                    }
                });
    }


    /**
     * 获取强弱密码修改
     */
    private void getPwdLevel(final String accessToken) {
        getApi(UserApi.class).getPwdLevel(getDefaultAddress() + Url.GET_PSD_LEVEL, Url.XMLHTTPREQUEST, accessToken)
                .compose(new ResponseTransformer<>(this.<IconBean>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<IconBean>() {
                    @Override
                    public void success(IconBean baseData) {
                        XLog.i("getPwdLevel--" + baseData.toString());
                        getSharedPrefs().edit().putString(Constant.PSD_LEVEL, baseData.getRecord()).apply();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }

                    @Override
                    public void onRequestAgain() {

                    }

                });
    }


    public void getAgreement() {

        getApi(CommonApi.class).getAgreement(getDefaultAddress() + Url.AGREEMENT)
                .compose(new ResponseTransformer<>(this.<AgreementBean>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<AgreementBean>(view) {
                    @Override
                    public void success(AgreementBean baseData) {
                        if (baseData.getRecords().size() == 0 || baseData.getRecords() == null) {
                            return;
                        }
                        //判断是否为4.5领展定制版本的协议
                        if (baseData.getRecords().size() > 1) {
                            baseData.setIsCustom("1");
                            for (AgreementBean.RecordsBean record : baseData.getRecords()) {
                                if (record.getCode().equals("PRIVACY_CONTENT")) {
                                    baseData.setContent(record.getValue());
                                } else if (record.getCode().equals("PRIVACY_VERSION")) {
                                    baseData.setVersion(record.getValue());
//                                    baseData.setVersion("V1.1");
                                } else if (record.getCode().equals("PRIVACY_NAME")) {
                                    baseData.setTitle(record.getValue());
                                } else if (record.getCode().equals("PRIVACY_NAME_EN")) {
                                    baseData.setTitle_en(record.getValue());
                                } else if (record.getCode().equals("PRIVACY_NAME_OTH")) {
                                    baseData.setTitle_ch(record.getValue());
                                }
                            }
                        } else {
                            baseData.setIsCustom("2");
                            baseData.setContent(baseData.getRecords().get(0).getValue());
                            baseData.setTitle("用户隐私协议");
                            baseData.setTitle_ch("用戶隱私協定");
                            baseData.setTitle_en("the user privacy agreement");
                        }


                        view.agreementContent(baseData);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                       // view.connentError(e);
                    }

                    @Override
                    public void onRequestAgain() {
                    }
                });
    }
    public void getAgreement(int type) {

        getApi(CommonApi.class).getAgreement(getDefaultAddress() + Url.AGREEMENT)
                .compose(new ResponseTransformer<>(this.<AgreementBean>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<AgreementBean>(view) {
                    @Override
                    public void success(AgreementBean baseData) {
                        if (baseData.getRecords().size() == 0 || baseData.getRecords() == null) {
                            return;
                        }
                        //判断是否为4.5领展定制版本的协议
                        if (baseData.getRecords().size() > 1) {
                            baseData.setIsCustom("1");
                            for (AgreementBean.RecordsBean record : baseData.getRecords()) {
                                if (record.getCode().equals("PRIVACY_CONTENT")) {
                                    baseData.setContent(record.getValue());
                                } else if (record.getCode().equals("PRIVACY_VERSION")) {
                                    baseData.setVersion(record.getValue());
//                                    baseData.setVersion("V1.1");
                                } else if (record.getCode().equals("PRIVACY_NAME")) {
                                    baseData.setTitle(record.getValue());
                                } else if (record.getCode().equals("PRIVACY_NAME_EN")) {
                                    baseData.setTitle_en(record.getValue());
                                } else if (record.getCode().equals("PRIVACY_NAME_OTH")) {
                                    baseData.setTitle_ch(record.getValue());
                                }
                            }
                        } else {
                            baseData.setIsCustom("2");
                            baseData.setContent(baseData.getRecords().get(0).getValue());
                            baseData.setTitle("用户隐私协议");
                            baseData.setTitle_ch("用戶隱私協定");
                            baseData.setTitle_en("the user privacy agreement");
                        }


                        view.agreementContent(baseData);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                         view.connentError(e);
                    }

                    @Override
                    public void onRequestAgain() {
                    }
                });
    }


    public void getXiYouSSOSetting() {
        getApi(UserApi.class).getXiYouSSOSetting(getDefaultAddress() + Url.XIYOU_ISOPENSETTING, Url.XMLHTTPREQUEST)
                .compose(new ResponseTransformer<>(this.<XiyouLoginBean>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<XiyouLoginBean>(view) {
                    @Override
                    public void success(XiyouLoginBean baseData) {
                        view.getXiYouSSOSettingSuccess(baseData.getRecord().flag);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }

                    @Override
                    public void onRequestAgain() {

                    }

                });


    }

    /**
     * 企业设置查询(现有接口)
     * "http://192.168.200.78"
     */


    /**
     * 手机短信登录 短信验证码生成
     */
    public void sendMessage(String phone) {
        HashMap<String, String> map = new HashMap();
        map.put("phone", phone);

        Map<String, RequestBody> stringRequestBodyMap = StringUtils.generateRequestBody(map);

        getApi(UserApi.class).sendMessage(getDefaultAddress() + Url.SENDMESSAGE_LOGIN, stringRequestBodyMap)
                .compose(new ResponseTransformer<>(this.<BaseData>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<BaseData>(view) {
                    @Override
                    public void success(BaseData baseData) {
                        if ("200".equals(baseData.getStatus())) {
                            view.sendSmsSuccess();
                        } else {
                            view.sendSmsFail();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        view.sendSmsFail();
                    }

                    @Override
                    public void onRequestAgain() {
                        view.sendSmsFail();
                    }

                });
    }


    /**
     * 检测当前用户 是否需要修改密码
     *
     * @param
     */
    public void checkBuUnamepwd(String username, String loginPwd, String phone) {
        HashMap<String, String> map = new HashMap();
        map.put("username", username);
        map.put("loginPwd", TextUtils.isEmpty(loginPwd) ? "" : AESUtil.encryptAESExpand(loginPwd)); //AES加密

        map.put("phone", TextUtils.isEmpty(phone) ? "" : AESUtil.encryptAESExpand(phone));

        map.put("defaultPwd", AESUtil.encryptAESExpand(UserHelper.getSysSettingsValueBycode("PWD_INIT")));  //初shi密码
        map.put("pwdFailureCount", UserHelper.getSysSettingsValueBycode("ACCOUNT_LOCK_THRESHOLD"));  //账号锁定阈值
        map.put("pwdLimitTime", UserHelper.getSysSettingsValueBycode("PWD_MAXIMUM_EXP")); //密码最长使用期限
        map.put("pwdOutTime", UserHelper.getSysSettingsValueBycode("PWD_EXP_ALARM"));  //密码过期告警
        map.put("forcePwd", UserHelper.getSysSettingsValueBycode("PWD_MODIFY_FORCE"));  //是否强制修改原始密码

        map.put("encrypted", "3");

        Map<String, RequestBody> stringRequestBodyMap = StringUtils.generateRequestBody(map);
        view.showLoading();
        Log.e("22222",new Gson().toJson(map));
        getApi(UserApi.class).checkBuUnamepwd(getDefaultAddress() + Url.CHECK_BY_UNAMEPWD,
                stringRequestBodyMap
        )
                .compose(new ResponseTransformer<>(this.<CheckByUnamepwdResponse>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<CheckByUnamepwdResponse>(view) {
                    @Override
                    public void success(CheckByUnamepwdResponse baseData) {
                        view.hideLoading();
                        if (baseData.getRecord() == null) {
                            view.checkBuUnamepwdSuccess("");
                        } else {
                            if (TextUtils.isEmpty(baseData.getRecord().getPwdChangeDec())) {
                                view.checkBuUnamepwdSuccess(baseData.getRecord().getLoginId());
                            } else {
                                view.checkBuUnamepwdFailure(baseData.getRecord().getPwdChangeDec(), baseData.getRecord().getLoginId());
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        view.checkBuUnamepwdSuccess("");
                        view.hideLoading();
                    }

                    @Override
                    public void onRequestAgain() {

                    }

                });
    }


    private void getTips() {
        ApiFactory.getFactory().create(UserApi.class).someTipsOrDec(getDefaultAddress() + Url.KEYDESC + "PWD_COMPLEXITY" + "&code=" + UserHelper.getSysSettingsValueBycode("PWD_COMPLEXITY"))
                .compose(new ResponseTransformer())
                .subscribe(new ResponseSubscriber<SysKeyDescBean>() {
                    @Override
                    public void success(SysKeyDescBean baseData) {
                        List<SysKeyDescBean.SettingInfo> records = baseData.getRecords();
                        if (records != null) {
                            //返回正则表达式
                            view.getTipsSuccess(records.get(0).getSpecialLabel());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }

                    @Override
                    public void onRequestAgain() {

                    }

                });
    }

    /**
     * accessToken	Long	是	操作令牌
     * username	String	是	用户名
     * loginOldPwd	String	否	旧密码
     * loginNewPwd	String	否	新密码
     * encrypted	String	否	是否加密	3  固定写死
     * type 1 是忘记密码  0不是
     */
    public void editPwd(String username, String loginOldPwd, String loginNewPwd, String type) {

        HashMap<String, String> map = new HashMap();
        map.put("username", username);
        map.put("loginOldPwd", AESUtil.encryptAESExpand(loginOldPwd)); //AES加密
        map.put("loginNewPwd", AESUtil.encryptAESExpand(loginNewPwd));
        map.put("defaultPwd", AESUtil.encryptAESExpand(UserHelper.getSysSettingsValueBycode("PWD_INIT")));  //初shi密码
        map.put("pwdComplexity", UserHelper.getSysSettingsValueBycode("PWD_COMPLEXITY"));  //复杂度
        map.put("pwdLen", UserHelper.getSysSettingsValueBycode("PWD_LEN"));  //密码长度
        map.put("type", type);
        map.put("encrypted", "3");

        Map<String, RequestBody> stringRequestBodyMap = StringUtils.generateRequestBody(map);

        ApiFactory.getFactory().create(UserApi.class).updatePwd(getDefaultAddress() + Url.UPDATE_PWD,
                "", stringRequestBodyMap)
                .compose(new ResponseTransformer<>(this.<BaseData>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<BaseData>() {
                    @Override
                    public void success(BaseData baseData) {
                        view.updatePwdSuccess();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }

                    @Override
                    public void onRequestAgain() {

                    }

                });
    }


    public void sysSettingsInfo() {
        getApi(UserApi.class).sysSettingsInfo(getDefaultAddress() + Url.SYS_SETTING, Url.XMLHTTPREQUEST, System.currentTimeMillis() + "")
                .compose(new ResponseTransformer<>(this.<SysSettingsInfoBean>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<SysSettingsInfoBean>(view) {
                    @Override
                    public void success(SysSettingsInfoBean baseData) {
                        if (baseData.getRecords() == null) {
                            view.sysSettingsInfoFaiture();
                        } else {
                            UserHelper.saveSysSettingsInfoBean(baseData);
                            view.sysSettingsInfoSucess();
                            view.sysSettingsInfoSuccess(baseData);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        view.sysSettingsInfoFaiture();
                        super.onError(e);
                    }

                    @Override
                    public void onRequestAgain() {
                        view.sysSettingsInfoFaiture();
                    }

                });
    }


    public void modifyPassword(final String initialPassword, final String newPassword, final String againPassword) {
        view.showLoading();
        getApi(UserApi.class).modifyPassword(getDefaultAddress() + Url.MODIFY_PASSWORD, Url.XMLHTTPREQUEST, UserHelper.getToken(), initialPassword, newPassword)
                .compose(new ResponseTransformer<>(this.<BaseData>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<BaseData>(view) {
                    @Override
                    public void success(BaseData baseData) {
                        view.ToastMessage(R.string.change_success);
                    }

                    @Override
                    public void onRequestAgain() {
                        modifyPassword(initialPassword, newPassword, againPassword);
                    }
                });
    }


}

